<?php
use think\facade\Db;
use Workerman\Worker;
use Workerman\Lib\Timer;
use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\MemberLever;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\common\models\Setup;
use addons\TfFutures\services\OrderService;

$worker        = new Worker();
$worker->name  = 'UserboomWorker';
$worker->count = 1;
$worker->onWorkerStart = function($worker)
{
    Timer::add(1, function() use ($worker)
    {
        //用户资产查询
    	$member_price = Member::find();
        $members = $member_price->all();
        //个人持仓订单
        foreach($members as $member)
        {
			//个人持仓订单
            $all_profit = Order::find()
                ->where(['state' => '持仓', 'member_id' => $member->member_id])
                ->select("sum(`profit`) as all_profit,member_id")
                ->asArray()
                ->all();
               
            if(empty($all_profit) ){
            	continue;
            }
            foreach ($all_profit as $k =>$v)
            {
                // 计算爆仓比
                $percentage = bcmul(bcadd($member['price'],$member['price_occupy'],4), bcdiv($setup['close'], 100, 4), 4);
                //判断该订单是否盈利
                if($v['all_profit']>0){
                	continue;
                }
                if (abs($v['all_profit']) > $percentage) {
                    //先查询所有订单
                    $order = Order::find()
                        ->where([
                            'member_id' => $v['member_id'],
                            'state'	  =>'持仓'
                        ])
                        ->all();
                    //循环平仓
                    foreach ($order as $key => $val) {
                        OrderService::OrderClose($val->id, NULL, '强制平仓');
                    }
                    // $lever = memberlever::find()->where(['id' => $v['lever_id'],'state'=>'正常'])->one();
                    // if(!empty($lever)){
                    // 	$lever->state = '禁用';
                    // 	$lever->save();
                    // }
                    
                }
            }
        }
    });
};
// 如果不是在根目录启动，则运行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

